package com.jiang.handler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.jiang.utils.MyStringUtils;
import com.jiang.vo.Book;

/**
 * @author Administrator
 *
 */
public class MyBookSaxHandler extends DefaultHandler {

	public List<Book> books = new ArrayList<Book>();
	private Book book = null;
	private String currentTag = null;

	@Override
	public void startDocument() throws SAXException {

	}

	@Override
	public void endDocument() throws SAXException {
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		// 判断是否遇到了book元素
		if ("book".equalsIgnoreCase(qName)) {
			book = new Book();
		} else {
			this.currentTag = qName;
		}
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		// 利用反射设置值
		try {
			if (this.currentTag != null && new String(ch, start, length).trim().length() > 0) {
				Method method = Book.class.getDeclaredMethod("set" + MyStringUtils.initcap(this.currentTag),
						String.class);
				method.invoke(this.book, new String(ch, start, length));
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {

		if ("book".equalsIgnoreCase(qName)) {
			books.add(book);
			book = null;

		}
	}

}
